package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyXiaoBeiQianBao;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeXiaoBeiQianBao;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformMultiPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMaskDataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMaskConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 小呗钱包
 *
 * 全流程 - 链接: https://apifox.com/apidoc/shared-21041cba-8bb7-4b18-9f5b-34e27b5cdbf4
 *         访问密码: JU9Nuz8M
 *
 * @author gwc
 * @create 2025-07-31 上午9:57
 */
@ApiPlan(productId = "386", type = ApiPlanConvertType.PLAT_PHONE_MASK)
public class ApiPlatXiaoBeiQianBaoPhoneMask implements ApiPlatformPhoneMaskConvertHandler {

    public static final String KEY = "Q7tchA1XTJhVVexi";
    public static final String CHANNEL_ID = "1951123691712225281";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        //  创建撞库实体类
        ApiPlatDataExchangeXiaoBeiQianBao XiaoBeiQianBaoData = new ApiPlatDataExchangeXiaoBeiQianBao();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        //  手机号前8位 (示例：13482437)，类型：string，必需
        XiaoBeiQianBaoData.setPhoneMd5(apiDataExchangeParameter.getPhoneMask());
        //  名字，类型：string，必需
        XiaoBeiQianBaoData.setName("默认姓名");
        //  年龄，类型：integer，必需
        XiaoBeiQianBaoData.setAge(apiFieldConverter.getAgeInt());
        //  性别：1男 0女，类型：integer，必需
        Integer sex = ChooseEq.create(apiDataExchangeParameter.getSex())
                .when("0", 1)
                .when("1", 0)
                .end(1);
        XiaoBeiQianBaoData.setSex(sex);
        //  所在城市 (如：成都市)，类型：string，必需
        XiaoBeiQianBaoData.setCity(apiDataExchangeParameter.getCity());
        //  城市代码，类型：string，必需
        XiaoBeiQianBaoData.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  省份名称，类型：string，必需
        XiaoBeiQianBaoData.setProvince(apiDataExchangeParameter.getProvinceName());
        //  芝麻分：1：无芝麻分，2：600分以下，3：600~650分，4：650~700分，5：700分以上，类型：integer，必需
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(1);
        XiaoBeiQianBaoData.setSesameScore(zhima);
        //  公积金：1：无，2：有，类型：integer，必需
        Integer gongjijin = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setFund(gongjijin);
        //  社保：1：无，2：6个月以下，3：6个月以上，类型：integer，必需
        Integer shebao = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 3)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setSocial(shebao);
        //  保单情况：1：无，2：有，类型：integer，必需
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setInsurance(baodanIs);
        //  房产情况：1：无，2：有，类型：integer，必需
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        XiaoBeiQianBaoData.setHouse(house);
        //  名下车产：1：无，2：有，类型：integer，必需
        Integer car = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setCar(car);
        //  职业身份：1-上班族，2-公务员/事业单位，3-私营业主，4-个体户，5-其他，类型：integer，必需
        Integer job = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 5)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 2)
                .when(apiDataExchangeParameter.getCareer(), "5", 4)
                .end(1);
        XiaoBeiQianBaoData.setProfession(job);
        //  借款金额（单位：元），默认值：10000，类型：integer，必需
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 30000)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 50000)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 100000)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 200000)
                .end(10000);
        XiaoBeiQianBaoData.setLoanAmount(money);
        //  用户IP，无IP则默认："127.0.0.1"，类型：string，必需
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getIp())) {
            XiaoBeiQianBaoData.setIp(apiDataExchangeParameter.getIp());
        } else {
            XiaoBeiQianBaoData.setIp("127.0.0.1");
        }
        //  加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(XiaoBeiQianBaoData));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelId", CHANNEL_ID);
            newMap.put("requestNo", IdUtils.getSimpleUuid());
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformMultiPhoneMaskDataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);

        if (jsonObject == null) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        //  获取响应数据
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        if(!Eq.object(resData.getString("status"), "1")) {
            return RespPlatformMultiPhoneMaskDataExchange.ofFail();
        }
        RespPlatformMultiPhoneMaskDataExchange respPlatformMultiPhoneMaskDataExchange = RespPlatformMultiPhoneMaskDataExchange.ofSuc();
        List<RespPlatformPhoneMaskDataExchange> listRespPlatformPhoneMaskDataExchange = CollUtils.newArrayList();

        //  获取携带参数
        String orderId = resData.getString("orderId");
        String productName = resData.getString("productName");
        String logo = resData.getString("logo");
        BigDecimal price = resData.getBigDecimal("price");
        String companyName = resData.getString("companyName");
        String url = resData.getString("url");
        //  用户协议
        List<ApiProtocol> protocolList = new ArrayList<>();
        //  获取协议
        JSONArray listProtocolResult = resData.getJSONArray("protocolList");
        IteratorUtils.array(listProtocolResult, (item, index) -> {
            JSONObject protocolObject = listProtocolResult.getJSONObject(index);
            ApiProtocol protocol = new ApiProtocol();
            protocol.setProtocolName(protocolObject.getString("contractName"));
            protocol.setProtocolUrl(protocolObject.getString("contractUrl"));
            protocolList.add(protocol);
        });
        //  获取手机号掩码
        List<String> listPhoneMd5 = new ArrayList<>();
        JSONArray jsonArray = resData.getJSONArray("phoneMd5List");
        IteratorUtils.array(jsonArray, (item, index) -> {
            String phoneMd5  = jsonArray.getString(index);
            listPhoneMd5.add(phoneMd5);
        });

        RespPlatformPhoneMaskDataExchange result = RespPlatformPhoneMaskDataExchange.of();
        result.setApplyId(orderId);
        result.setProductName(productName);
        result.setProtocolList(protocolList);
        result.setListPhoneMd5(listPhoneMd5);
        result.setDisplayName(companyName);
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setCallUrl(url);
        listRespPlatformPhoneMaskDataExchange.add(result);

        respPlatformMultiPhoneMaskDataExchange.setListPhoneMask(listRespPlatformPhoneMaskDataExchange);

        return respPlatformMultiPhoneMaskDataExchange;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        //  创建进件实体类
        ApiPlatApplyXiaoBeiQianBao XiaoBeiQianBaoData = new ApiPlatApplyXiaoBeiQianBao();
        //  拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  手机号明文 类型：string 必需
        XiaoBeiQianBaoData.setPhone(apiApplyParameter.getPhone());
        //  姓名 类型：string 必需
        XiaoBeiQianBaoData.setName(apiApplyParameter.getUserName());
        //  年龄 类型：integer 必需
        XiaoBeiQianBaoData.setAge(apiFieldConverter.getAgeInt());
        //  性别：1男，0女 类型：integer 必需
        Integer sex = ChooseEq.create(apiApplyParameter.getSex())
                .when("0", 1)
                .when("1", 0)
                .end(1);
        XiaoBeiQianBaoData.setSex(sex);
        //  所在城市（如：成都市） 类型：string 必需
        XiaoBeiQianBaoData.setCity(apiApplyParameter.getCity());
        //  地区代码 类型：string 必需
        XiaoBeiQianBaoData.setCityCode(apiApplyParameter.getAreaCode());
        //  省份名称 类型：string 必需
        XiaoBeiQianBaoData.setProvince(apiApplyParameter.getProvinceName());
        //  芝麻分：1：无芝麻分 2：600分以下 3：600~650分 4：650~700分 5：700分以上 类型：integer 必需
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(1);
        XiaoBeiQianBaoData.setSesameScore(zhima);
        //  公积金：1：无 2：有 类型：integer 必需
        Integer gongjijin = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 1)
                .when(apiApplyParameter.getProvidentFund(), "2", 2)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setFund(gongjijin);
        //  社保：1：无 2：6个月以下 3：6个月以上 类型：integer 必需
        Integer shebao = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 1)
                .when(apiApplyParameter.getSocialSecurity(), "2", 2)
                .when(apiApplyParameter.getSocialSecurity(), "3", 3)
                .when(apiApplyParameter.getSocialSecurity(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setSocial(shebao);
        //  保单情况：1：无 2：有 类型：integer 必需
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setInsurance(baodanIs);
        //  房产情况：1：无 2：有 类型：integer 必需
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 2)
                .end(1);
        XiaoBeiQianBaoData.setHouse(house);
        //  名下车产：1：无 2：有 类型：integer 必需
        Integer car = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 1)
                .when(apiApplyParameter.getCarInfo(), "2", 2)
                .when(apiApplyParameter.getCarInfo(), "3", 2)
                .when(apiApplyParameter.getCarInfo(), "4", 2)
                .end(1);
        XiaoBeiQianBaoData.setCar(car);
        //  职业身份：1-上班族 2-公务员/事业单位 3-私营业主 4-个体户 5-其他 类型：integer 必需
        Integer job = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 5)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 2)
                .when(apiApplyParameter.getCareer(), "5", 4)
                .end(1);
        XiaoBeiQianBaoData.setProfession(job);
        //  借款金额（单位：元） 默认：10000 类型：integer 必需
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 30000)
                .when(apiApplyParameter.getLoanAmount(), "2", 50000)
                .when(apiApplyParameter.getLoanAmount(), "3", 100000)
                .when(apiApplyParameter.getLoanAmount(), "4", 200000)
                .end(10000);
        XiaoBeiQianBaoData.setLoanAmount(money);
        //  用户IP 无IP则默认："127.0.0.1" 类型：string 必需
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            XiaoBeiQianBaoData.setIp(apiApplyParameter.getIp());
        } else {
            XiaoBeiQianBaoData.setIp("127.0.0.1");
        }
        //  加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(XiaoBeiQianBaoData));
        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("channelId", CHANNEL_ID);
            newMap.put("requestNo", IdUtils.getSimpleUuid());
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMaskApply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 200)) {
            return RespPlatformPhoneMaskApply.ofFail();
        }
        return RespPlatformPhoneMaskApply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
